<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<div id="app">
    <input type="text" v-model="msg">
    <button @click="sendMessage()">发消息</button>
    <button @click="socket.close()">关闭连接</button>
</div>
</body>
<script src="https://cdn.bootcss.com/sockjs-client/1.3.0/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
<script>


    var vm = new Vue({
        el:"#app",
        data:{
            msg:"",
            socket:null
        },
        methods:{
            openSocket() {
                if(typeof(WebSocket) == "undefined") {
                    console.log("您的浏览器不支持WebSocket");
                }else{
                    console.log("您的浏览器支持WebSocket");
                    //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
                    var socketUrl="ws://localhost:8080/websocket";
                    if(this.socket!=null){
                        this.socket.close();
                        this.socket=null;
                    }
                    //初始化websocket实例对象
                    this.socket = new WebSocket(socketUrl);
                    //打开事件
                    this.socket.onopen = function() {
                        console.log("websocket已打开");
                    };
                    //获得消息事件
                    this.socket.onmessage = function(msg) {
                        //服务端回传的消息
                        console.log(msg.data);
                    };
                    //关闭事件
                    this.socket.onclose = function() {
                        console.log("websocket已关闭");
                    };
                    //发生了错误事件
                    this.socket.onerror = function() {
                        console.log("websocket发生了错误");
                    }
                }
            },
            sendMessage() {
                if(typeof(WebSocket) == "undefined") {
                    console.log("您的浏览器不支持WebSocket");
                }else {

                    this.socket.send(this.msg);
                }
            }



        },
        created(){//页面加载
            this.openSocket();
        }
    })

</script>

</html>